package com.hq.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * Created by XQ on 2015/8/3.
 */
public class FileUploadUtil {
    public final static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);

    public static Map<String, String> upload(HttpServletRequest request, String filePath) throws Exception {

        CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getSession().getServletContext());
        Map<String, String> result = new HashMap<String, String>();
        String url = "";

        if (cmr.isMultipart(request)) { // 判断是否有文件

            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
            Iterator<String> files = mRequest.getFileNames();

            while (files.hasNext()) {

                String paramName = files.next(); // 参数name值
                MultipartFile mFile = mRequest.getFile(paramName); // 获取文件
                if (mFile != null && !mFile.isEmpty()) { // 判断文件不为空

                    try {

                        String location = request.getSession().getServletContext().getRealPath("/") + filePath;
                        if (!new File(location).exists()){
                            File directory = new File(location);
                            directory.mkdirs();
                        }

                        String fileName = UUID.randomUUID() + "-" + mFile.getOriginalFilename();
                        File localFile = new File( location + "/" + fileName);
                        mFile.transferTo(localFile);
                        url = request.getScheme() + "://" + request.getServerName()
                                + ":" + request.getServerPort() + request.getContextPath() + filePath + "/" + fileName;
                        result.put(paramName, url);
                    } catch (Exception e) {
                        logger.error("文件上传失败：" + mFile.getOriginalFilename(), e);
                        throw new Exception("文件上传失败：" + mFile.getOriginalFilename());
                    }
                }
            }
        }
        return result;
    }
}
